// src/main/java/com/xxxy/ljh/myapplication/activity/detail/ActivityDetailActivity.java
package com.xxxy.ljh.myapplication.activity.detail;

import static com.xxxy.ljh.myapplication.nav.MineFragment.LOGIN_REQUEST_CODE;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.xxxy.ljh.myapplication.R;
import com.xxxy.ljh.myapplication.activity.login.LoginActivity;
import com.xxxy.ljh.myapplication.Dao.SignupDao;
import com.xxxy.ljh.myapplication.Dao.UserDao;
import com.xxxy.ljh.myapplication.DaoImpl.SignupDaoImpl;
import com.xxxy.ljh.myapplication.DaoImpl.UserDaoImpl;
import com.xxxy.ljh.myapplication.model.ActivityItem;
import com.xxxy.ljh.myapplication.model.Signup;

public class ActivityDetailActivity extends AppCompatActivity {

    private TextView titleTextView;
    private TextView timeTextView;
    private TextView locationTextView;
    private TextView descriptionTextView;
    private TextView participantsTextView;

    private EditText etSpecialty;
    private RadioGroup radioGroupVehicle;
    private EditText etRemarks;
    private Button btnSubmitApplication;

    private ActivityItem activityItem;
    private static final int LOGIN_REQUEST_CODE = 1001;

    // 数据访问对象
    private SignupDao signupDao;
    private UserDao userDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        // 初始化DAO - 使用具体实现类
        signupDao = new SignupDaoImpl(this);
        userDao = new UserDaoImpl(this);

        // 初始化视图组件
        initViews();

        // 获取传递过来的ActivityItem数据
        activityItem = (ActivityItem) getIntent().getSerializableExtra("activity_item");

        // 显示活动详情
        if (activityItem != null) {
            displayActivityDetails(activityItem);
            setupClickListeners();
        }
    }

    private void initViews() {
        titleTextView = findViewById(R.id.detailTitleTextView);
        timeTextView = findViewById(R.id.detailTimeTextView);
        locationTextView = findViewById(R.id.detailLocationTextView);
        descriptionTextView = findViewById(R.id.detailDescriptionTextView);
        participantsTextView = findViewById(R.id.detailParticipantsTextView);

        etSpecialty = findViewById(R.id.etSpecialty);
        radioGroupVehicle = findViewById(R.id.radioGroupVehicle);
        etRemarks = findViewById(R.id.etRemarks);
        btnSubmitApplication = findViewById(R.id.btnSubmitApplication);
    }

    private void displayActivityDetails(ActivityItem activityItem) {
        titleTextView.setText(activityItem.getTitle());
        timeTextView.setText(activityItem.getDateTime());
        locationTextView.setText(activityItem.getLocation());
        descriptionTextView.setText(activityItem.getDescription());

        // 获取报名人数
        int participantCount = signupDao.getSignupCount(activityItem.getId());
        participantsTextView.setText("已报名: " + participantCount + "人");
    }

    private void setupClickListeners() {
        btnSubmitApplication.setOnClickListener(v -> {
            // 检查用户是否已登录
            if (!isUserLoggedIn()) {
                // 用户未登录，跳转到登录页面
                Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
                Intent loginIntent = new Intent(this, LoginActivity.class);
                startActivityForResult(loginIntent, LOGIN_REQUEST_CODE);
                return;
            }

            // 用户已登录，执行报名逻辑
            submitApplication();
        });
    }

    /**
     * 检查用户是否已登录
     * @return true表示已登录，false表示未登录
     */
    private boolean isUserLoggedIn() {
        // 改为与 ClubFragment 一致的检查方式
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        return prefs.getBoolean("is_logged_in", false);
    }


    /**
     * 执行报名逻辑
     */
    /**
     * 执行报名逻辑
     */
    private void submitApplication() {
        try {
            // 获取当前登录用户ID（这里不再重复检查登录状态）
            SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
            int userId = prefs.getInt("user_id", -1);

            if (userId == -1) {
                Toast.makeText(this, "用户信息异常，请重新登录", Toast.LENGTH_SHORT).show();
                return;
            }

            // 检查是否已经报名
            if (signupDao.hasSignedUp(activityItem.getId(), userId)) {
                Toast.makeText(this, "您已经报名过此活动了！", Toast.LENGTH_SHORT).show();
                return;
            }

            // 获取用户填写的报名信息
            String specialty = etSpecialty.getText().toString().trim();
            String vehicleNeeded = radioGroupVehicle.getCheckedRadioButtonId() == R.id.rbYesVehicle ? "需要" : "不需要";
            String remarks = etRemarks.getText().toString().trim();

            // 组装报名信息
            String signupInfo = "特长：" + specialty + "；车辆需求：" + vehicleNeeded + "；备注：" + remarks;

            // 创建 Signup 对象
            Signup signup = new Signup();
            signup.setActivityId(activityItem.getId());
            signup.setUserId(userId);
            signup.setSignupInfo(signupInfo);
            signup.setSignupStatus(0); // 0表示待审核
            signup.setAttendanceStatus(0); // 0表示未签到
            signup.setPoints(0); // 初始积分为0

            // 提交报名信息到数据库
            long result = signupDao.signupForActivity(signup);

            if (result > 0) {
                Toast.makeText(this, "报名成功！", Toast.LENGTH_LONG).show();

                // 更新报名人数显示
                int participantCount = signupDao.getSignupCount(activityItem.getId());
                participantsTextView.setText("已报名: " + participantCount + "人");

                // 清空表单
                etSpecialty.setText("");
                radioGroupVehicle.clearCheck();
                etRemarks.setText("");
            } else {
                Toast.makeText(this, "报名失败，请重试", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "报名失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        // 每次页面可见时检查登录状态
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 处理登录结果 - 与 ClubFragment 保持一致
        if (requestCode == LOGIN_REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                String username = data.getStringExtra("logged_in_user");
                if (username != null) {
                    // 保存登录状态 - 与 ClubFragment 保持一致
                    SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
                    prefs.edit()
                            .putBoolean("is_logged_in", true)
                            .putString("username", username)
                            .apply();

                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                    // 登录成功后继续执行报名操作
                    submitApplication();
                }
            }
        }
    }


}
